package com.ledi.guns.modular.ledipay.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ledi.guns.common.exception.BizExceptionEnum;
import com.ledi.guns.common.exception.BussinessException;
import com.ledi.guns.common.persistence.dao.UserMapper;
import com.ledi.guns.common.persistence.model.User;
import com.ledi.guns.core.base.controller.BaseController;
import com.ledi.guns.core.base.tips.SuccessTip;
import com.ledi.guns.core.base.tips.Tip;
import com.ledi.guns.core.redis.KeyValueDAO;
import com.ledi.guns.core.shiro.ShiroKit;
import com.ledi.guns.core.shiro.ShiroUser;
import com.ledi.guns.core.support.HttpKit;
import com.ledi.guns.core.util.DateUtil;
import com.ledi.guns.core.util.SystemConstans;
import com.ledi.guns.core.util.ToolUtil;
import com.ledi.guns.modular.ledipay.service.IUserService;

/**
 * 文件名称： com.ledi.guns.modular.ledipay.controller.UserInfoController.java<br/>
 * 初始作者： 钟小平<br/>
 * 创建日期： 2017年12月6日<br/>
 * 功能说明： 用户管理Controller<br/>
 * =================================================<br/>
 * 修改记录：<br/>
 * 修改作者 日期 修改内容<br/>
 * ================================================<br/>
 * Copyright (乐迪教育科技有限公司-幼儿事业部) 2017-2018.All rights reserved.<br/>
 */
@RestController
@Api
@RequestMapping("/restApi/user")
public class UserInfoController extends BaseController {

	private static String PREFIX = "/system/user/";

	@Resource
	private UserMapper userMapper;

	@Resource
	private IUserService iUserService;

	@Resource
	private KeyValueDAO keyValueDAO;

	@Value("${version.update.time}")
	private String updateTime;

	@Value("${version.update.content}")
	private String updateContent;

	/**
	 * @api {POST} /restApi/user/changePwd 修改密码
	 * @apiVersion 1.0.0
	 * @apiGroup system
	 * @apiParam {String } password 原始密码
	 * @apiParam {String } newPassword 新密码
	 * @apiParam {String } confirmPassword 确认新密码
	 * @apiName changePwd
	 * @apiSuccessExample {json} Success-Response:
	 *                    HTTP/1.1 200 OK
	 *                    {
	 *                    "code": 200,
	 *                    "message": "成功"
	 *                    }
	 */
	@RequestMapping(value = "/changePwd", method = RequestMethod.POST)
	public Object changePwd(@RequestParam String password, @RequestParam String newPassword,
			@RequestParam String confirmPassword) {

		ShiroUser currentUser = ShiroKit.getUser();
		User user1 = userMapper.selectById(currentUser.getId());
		if (1 != user1.getStatus()) {
			throw new BussinessException(BizExceptionEnum.TWO_DELETE_MATCH);
		}
		if (!newPassword.equals(confirmPassword)) {
			throw new BussinessException(BizExceptionEnum.TWO_PWD_NOT_MATCH);
		}
		Integer userId = ShiroKit.getUser().getId();
		User user = userMapper.selectById(userId);
		String oldMd5 = ShiroKit.md5(password, user.getSalt());
		if (user.getPassword().equals(oldMd5)) {
			String newMd5 = ShiroKit.md5(newPassword, user.getSalt());
			user.setPassword(newMd5);
			user.updateById();
			String key = SystemConstans.USER_SESSION_STATUS.replaceAll("\\{0\\}", HttpKit.getRequest().getSession().getId());
			keyValueDAO.set(key, SystemConstans.USER_ACOUNT_STATUS_1, 0L);
			return SuccessTip.buildSuccess();
		} else {
			throw new BussinessException(BizExceptionEnum.OLD_PWD_NOT_RIGHT);
		}
	}

	/**
	 * @api {GET} /restApi/user/forgetPwd/{mobile} 忘记密码发送用户短信验证码
	 * @apiVersion 1.0.0
	 * @apiGroup system
	 * @apiParam {String } mobile 手机号码
	 * @apiName forgetPwd
	 * @apiSuccessExample {json} Success-Response:
	 *                    HTTP/1.1 200 OK
	 *                    {
	 *                    "code": 200,
	 *                    "message": "成功"
	 *                    }
	 */
	@RequestMapping(value = "/forgetPwd/{mobile}", method = RequestMethod.GET)
	public Object forgetPwd(@PathVariable String mobile) {

		iUserService.forgetPassword(mobile);
		return SuccessTip.buildSuccess();
	}

	/**
	 * @api {GET} /restApi/user/checkUserKaptcha/{mobile}/{password}/{kaptcha} 校验用户手机和验证码
	 * @apiVersion 1.0.0
	 * @apiGroup system
	 * @apiParam {String } mobile 手机号码
	 * @apiParam {String } kaptcha 用户手机收到的验证码
	 * @apiParam {String } password 更新的密码
	 * @apiName checkUserKaptcha
	 * @apiSuccessExample {json} Success-Response:
	 *                    HTTP/1.1 200 OK
	 *                    {
	 *                    "code": 200,
	 *                    "message": "成功"
	 *                    }
	 */
	@RequestMapping(value = "/checkUserKaptcha/{mobile}/{password}/{kaptcha}", method = RequestMethod.GET)
	public Object checkUserKaptcha(@PathVariable String mobile, @PathVariable String password,
			@PathVariable String kaptcha) {

		iUserService.checkUserKaptcha(mobile, password, kaptcha);
		return SuccessTip.buildSuccess();

	}

	/**
	 * @api {GET} /restApi/user/info 用户基本信息
	 * @apiVersion 1.4.0
	 * @apiGroup system
	 * @apiSuccess {Long } id 主键ID
	 * @apiSuccess {String } agentId 账号
	 * @apiSuccess {String } avatar 头像
	 * @apiSuccess {String} birthday 生日
	 * @apiSuccess {String} phone 电话
	 * @apiSuccess {String } email 邮箱
	 * @apiSuccess {Byte } name 名称
	 * @apiSuccess {Date } createTime 创建时间
	 * @apiSuccess {String } createrName 创建者名称
	 * @apiSuccess {int } versionNo 版本号
	 * @apiSuccess {int } schoolId 学校id
	 * @apiSuccess {int } updateContent 版本更新信息
	 * @apiName info
	 * @apiSuccessExample {json} Success-Response:
	 *                    HTTP/1.1 200 OK
	 *                    {
	 *                    "updateContent": "1、新增学生管理。2、班级管理。3新增可选项缴费",
	 *                    "user": {
	 *                    "account": "15655555555",
	 *                    "agentId": "",
	 *                    "alipayPid": "2342344444444444",
	 *                    "avatar": "",
	 *                    "birthday": "",
	 *                    "comment": "",
	 *                    "createid": 215,
	 *                    "createtime": "2018-07-25 20:11:18",
	 *                    "deptid": 28,
	 *                    "email": "",
	 *                    "id": 221,
	 *                    "name": "sdfsdfsdf",
	 *                    "phone": "15655555555",
	 *                    "roleid": "6",
	 *                    "schoolId": 97,
	 *                    "sex": "",
	 *                    "status": 1,
	 *                    "updateid": "",
	 *                    "updatetime": "",
	 *                    "version": 0
	 *                    }
	 *                    }
	 */
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public Object userInfo() {

		Integer userId = ShiroKit.getUser().getId();
		if (ToolUtil.isEmpty(userId)) {
			throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
		}
		User user = userMapper.selectById(userId);
		Map<String, Object> result = new HashMap<>();
		result.put("user", user);
		String key = SystemConstans.USER_VERSION_UPDATE.replaceAll("\\{0\\}", userId + "").replaceAll("\\{1\\}", updateTime);
		Date time = DateUtil.parse(updateTime, "yyyy-MM-dd hh:mm:ss");
		if (time.before(new Date())) {
			if (keyValueDAO.get(key) == null) {
				result.put("updateContent", updateContent);
				keyValueDAO.set(key, updateContent, 0L);
			} else {
				result.put("updateContent", "");
			}
		} else {
			keyValueDAO.delete(key);
			result.put("updateContent", "");
		}
		return result;
	}

	/**
	 * @api {POST} /restApi/user/uploadUserLogo 更新用户头像
	 * @apiVersion 1.5.0
	 * @apiGroup system
	 * @apiParam {String } avatar 头像文件流
	 * @apiSuccess {int } id 用户id
	 * @apiName uploadUserLogo
	 **/
	// @Permission
	@ApiOperation("uploadUserLogo")
	@ApiImplicitParams({
		@ApiImplicitParam(dataType = "file", name = "avatar", required = true, paramType = "form")
	})
	@RequestMapping(value = "/uploadUserLogo", method = RequestMethod.POST)
	public Tip uploadUserLogo(@RequestParam("avatar") MultipartFile file) throws IOException {

		return SuccessTip.buildSuccess(iUserService.updateUser(file));
	}

	/**
	 * @api {GET} /restApi/user/noTip 提示信息
	 * @apiVersion 1.4.0
	 * @apiGroup system
	 * @apiParam {Long } flag 不再提醒(可不传)
	 * @apiSuccess {int } tip 提示信息
	 * @apiName noTip
	 **/
	@RequestMapping(value = "/noTip", method = RequestMethod.GET)
	public Object noTip(@RequestParam(required = false) Integer flag) {

		Integer userId = ShiroKit.getUser().getId();
		if (ToolUtil.isEmpty(userId)) {
			throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
		}
		Map<String, Object> result = new HashMap<>();
		String key = SystemConstans.USER_NO_TIP.replaceAll("\\{0\\}", userId + "");
		if (flag == null) {
			if (keyValueDAO.get(key) != null) {
				result.put("tip", "");
				return result;
			}
			result.put("tip", SystemConstans.TIP);
			return result;
		}
		if (keyValueDAO.get(key) == null) {
			keyValueDAO.set(key, flag + "", 0L);
			result.put("tip", "");
		}
		return result;
	}
}
